package pattern.bio_httpserver;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * @author xiawen yang
 * @date 2021/12/16 下午3:09
 */
public class HttpTask implements Runnable{

    private Socket socket;

    public HttpTask(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        if (socket == null) {
            throw new IllegalArgumentException("socket can't be null.");
        }

        OutputStream outputStream = null;
        try {
            outputStream = socket.getOutputStream();
            PrintWriter printWriter = new PrintWriter(outputStream);

            // 根据请求结果进行响应，省略返回
            String result = "...";
            HttpMessageParser.Request httpRequest = HttpMessageParser.parse2Request(socket.getInputStream());
            String httpResponse = HttpMessageParser.buildResponse(httpRequest, result);
            printWriter.print(httpResponse);
            printWriter.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
